﻿using System;
using System.Data.SqlClient;
using System.Linq;
using IntraVision.Web;
using IntraVision.Web.Security;
using Model;

[AllowedRole("IsAdmin")]
public class WorkflowController : EntityListController<Workflow, NotarialServiceDataContext>
{
    protected override void EntityLoaded(NotarialServiceDataContext dc, Workflow workflow)
    {
        RegisterStylesheet("workflow/workflow.css");
        RegisterScript("jquery.multipleselect.js", "workflow/workflow.js");

        ViewData["statuses"] = (from s in dc.Status orderby s.SortOrder select s).ToList();
        ViewData["permissions"] = (from p in dc.Permissions orderby p.Name select p).ToList();
    }

    public void Default()
    {
        View();
    }

    protected override void BeforeSubmit(NotarialServiceDataContext dc, Workflow workflow)
    {
        #region Сохранить правила переходов

        var statuses = (from s in dc.Status select s.Id).ToList();
        statuses.Insert(0, 0);

        foreach (int fs in statuses)
        {
            foreach (int ts in statuses)
            {
                if (ts == 0) continue;
                int? fromStatus = null;
                if (fs > 0) fromStatus = fs;
                string key = string.Format("rule_{0}_{1}", fs, ts);

                //Получим через запятую роли, которые могут совершать перевод
                int[] ids = RequestHelper.GetIdsFromString(Request[key]);

                //Удалить лишние переходы
                dc.WorkflowStatusMatrixes.DeleteAllOnSubmit((from wsm in dc.WorkflowStatusMatrixes where !ids.Contains(wsm.PermissionId.Value) && wsm.WorkflowId == workflow.Id && wsm.ToStatusId == ts && object.Equals(wsm.FromStatusId, fromStatus) select wsm));

                //Создать новые переходы
                foreach (int id in ids)
                {
                    var rule = new WorkflowStatusMatrix();
                    rule.WorkflowId = workflow.Id;
                    rule.FromStatusId = fromStatus;
                    rule.ToStatusId = ts;
                    rule.PermissionId = id;

                    if (rule.FromStatusId == 0) rule.FromStatusId = null;
                    //Добавим правило только если оно не существует
                    if (!dc.WorkflowStatusMatrixes.Any(wsm => wsm.PermissionId == rule.PermissionId && wsm.WorkflowId == rule.WorkflowId && wsm.ToStatusId == rule.ToStatusId && object.Equals(wsm.FromStatusId, rule.FromStatusId)))
                        workflow.WorkflowStatusMatrix.Add(rule); 
                }
            }
        }
        
        #endregion
    }

    public void View()
    {
        using (var dc = new NotarialServiceDataContext())
        {
            string id = "";
            //на время пока существует единственный workflow для всех
            var wf = dc.Workflows.FirstOrDefault();
            if (wf != null)
            {
                id = wf.Id.ToString();
                View(id);
            }
            else
                Create();
        }
    }

    public override void List()
    {
        return;
    }
}
